package com.gph.saviorframework.security.web.editor;

import com.gph.saviorframework.common.model.Module;
import com.gph.saviorframework.security.service.ModuleService;

import java.beans.PropertyEditorSupport;

public class ModuleEditor extends PropertyEditorSupport {

    private ModuleService moduleService;

    /**
     * @param moduleService
     */
    public ModuleEditor(ModuleService moduleService) {
        this.moduleService = moduleService;
    }

    /**
     * @return
     * @see PropertyEditorSupport#getAsText()
     */
    @Override
    public String getAsText() {
        if (getValue() instanceof Module) {
            return ((Module) getValue()).getId().toString();
        }
        return null;
    }

    /**
     * @param text
     * @throws IllegalArgumentException
     * @see PropertyEditorSupport#setAsText(String)
     */
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        Object module = moduleService.get(text);
        if (module != null) {
            setValue(module);
        } else {
            setValue(new Module(text));
        }
    }

}
